'use strict';

const Controller = require('egg').Controller;

class HomeService extends Controller {
  async user() {
    const { ctx, app } = this;
    const QUERY_STR = 'id, name';
    const sql = `select ${QUERY_STR} from list`; // 获取ID的sql语句

    try {
      // mysql 实例已经挂载到 app 对象下，可以通过 app.mysql 获取到。
      return await app.mysql.query(sql);
    } catch (e) {
      console.log(e);
      return null;
    }
  }

  async addUser(name) {
    const { ctx, app } = this;
    try {
      // mysql 实例已经挂载到 app 对象下，可以通过 app.mysql 获取到。
      return await app.mysql.insert('list', { name });
    } catch (e) {
      console.log(e);
      return null;
    }
  }

  async editUser(id, name) {
    const { ctx, app } = this;

    try {
      return await app.mysql.update('list', { name }, {
        where: { id },
      });
    } catch (e) {
      console.log(e);
      return null;
    }
  }


  async deleteUser(id) {
    const { ctx, app } = this;
    try {
      return await app.mysql.delete('list', { id });
    } catch (e) {
      console.log(e);
      return null;
    }
  }
}

module.exports = HomeService;
